package com.eric.nioclient.service.packet;

import io.netty.buffer.ByteBuf;

import java.io.UnsupportedEncodingException;

public abstract  class Packet {
      
    public void writeToBuff(ByteBuf buf){
        buf.writeInt(getPacketType().getType());
        buf.writeInt(getBodyLength());
        writePacketMsg(buf);  
    }  
      
    abstract public void  writePacketMsg(ByteBuf buf);  
      
    abstract public void  readFromBuff(ByteBuf buf);  
      
    abstract public PacketType  getPacketType();  
      
    abstract public void execPacket();  
      
    protected  String readUTF8(ByteBuf buf){  
        int strSize = buf.readInt();  
        byte[] content = new byte[strSize];  
        buf.readBytes(content);  
        try {  
            return new String(content,"UTF-8");  
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();  
            return "";  
        }  
          
    }  
      
    protected  int writeUTF8(ByteBuf buf,String msg){
        byte[] content ;  
        try {  
            content = msg.getBytes("UTF-8");  
            buf.writeInt(content.length);  
            buf.writeBytes(content);
            return content.length + 4;
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }
        return 0;
    }

    protected int getBodyLength(){
        return 0;
    }

    public Packet obtain(Object ...args){
        return null;
    }
      
}  